<?php
class CProductreview extends Zend_Db_Table
{
	protected $_name;
	protected $_primary;

	public function __construct()
	{
		$this->_name = R_PRE."product_review";
		$this->_primary = "product_review_id";
		parent::__construct();
	}
	
	public function add($row)
	{
		return $this->insert($row);
	}
	
	public function isExist($itemId, $uid, $orderId)
	{
		$where = array('itemid = ?'=>$itemId, 'uid = ?'=>$uid, 'orderid = ?'=>$orderId);
		$row = $this->fetchAll($where);
		return $row;
	}
	
	public function fetchReview($page, $pageNum, $itemId)
	{
		$where = array('itemid = ?'=>$itemId, 'uid > ?'=>0 );
		$order = 'product_review_id desc';
		
		$offset = ($page -1) * $pageNum;
		return $this->fetchAll($where, $order, $pageNum, $offset);
	}
	
	public function getPageCount($itemId, $isTrue = 0)
	{
		$where = array('itemid = ?'=>$itemId);
		if ($isTrue) {
			$where['uid > ?'] = 0;
		}
		$result = $this->fetchAll($where);
		return count($result);
	}
	
	public function delete($itemidArray)
	{		
		$db=$this->getAdapter();
		$itemidString=join(',',$itemidArray);
		$result=$db->query("DELETE FROM $this->_name WHERE product_review_id IN ($itemidString)");
		return $result;
	}	
	
	public function average($itemid)
	{
		$sql = 'select avg(product_score) as product_avg, avg(ship_score) as ship_avg, avg(overall_score) as overall_avg from ' . $this->_name . ' where itemid = ' . intval($itemid);
		$db = $this->getAdapter();
		return $db->fetchAll($sql);
	}
	
	public function allcount($score, $itemid, $all = 0)
	{
		$sql = "select count(overall_score) as count from " . $this->_name . " where itemid = " . $itemid;
		if (!$all) {
			$sql .= " and overall_score = " . $score;
		}
		
		$db = $this->getAdapter();
		return $db->fetchAll($sql);
	}
	
	public function getReviewCount($itemid, $title, $viewNum, $currentCount)
	{
		$len = strlen($title)/8;
		$len = ceil($len);
		$dateLen = (time() - strtotime('2011-12-10'))/3600/24;
		$dateLen = ceil($dateLen);
		$reviewCountNeed = ($len + $dateLen + $viewNum) * 0.8;
		$reviewCountNeed = ceil($reviewCountNeed);
		return $reviewCountNeed;
	}
	
	public function addReviewRand($itemid, $title, $viewNum, $currentCount)
	{
		$len = strlen($title)/8;
		$len = ceil($len);
		$dateLen = (time() - strtotime('2011-12-10'))/3600/24;
		$dateLen = ceil($dateLen);
		$reviewCountNeed = ($len + $dateLen + $viewNum) * 0.8;
		$reviewCountNeed = ceil($reviewCountNeed);
		$diff = $reviewCountNeed - $currentCount;
		if ($diff > 0) {
			for($i = 0; $i < $diff; $i++) {
				$row = array('itemid'=>$itemid, 'product_score'=>rand(30,50)/10, 'ship_score'=>rand(30,50)/10, 'overall_score'=>rand(30,50)/10, 'comments'=>'', 'add_time'=>time());
				$this->add($row);
			}
		}	
	}
}